package com.naive.imperative.view;

import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;

import com.naive.imperative.program.BlockChangeEvent;
import com.naive.imperative.program.ChangeEvent;
import com.naive.imperative.program.EvaluatableOperation;
import com.naive.imperative.program.Operation;
import com.naive.imperative.program.OperationBlock;
import com.naive.imperative.program.Program;
import com.naive.imperative.program.ProgramListener;

public class ProgramView extends View {
	private Program program;
	private RootRenderer rootRenderer;
	private ProgramListener progListener;
	private RendererFactory rendererFactory;

	public ProgramView(Context context) {
		super(context);
	}
	
//	@Override
//	public boolean onTouchEvent(MotionEvent event) {
//		return super.onTouchEvent(event);
//	}
//
	private RenderingContext prepareContext(Canvas c) {
		return new RenderingContext();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		rootRenderer.draw(prepareContext(canvas));
	}
	
	protected OperationRenderer locate(Operation o) {
		return null;
	}
//
//	protected Operation locate(OperationRenderer d) {
//		return null;
//	}

	public Program getProgram() {
		return program;
	}

	public void setProgram(Program p) {
		if (null != program) {
			program.removeProgramListener(progListener);
		}
		rootRenderer = null;
		program = p;
		if (null != program) {
			program.addProgramListener(progListener);
			rootRenderer = new RootRenderer(program.getRootContainer());
		}
	}

	private class Handler implements ProgramListener {
		
		public void operationChanged(ChangeEvent e) {
			Operation op = e.getOperation();
			OperationRenderer d = rendererFactory.create(op);
			rootRenderer.locate(e.getParent()).replace(op, d);
			rootRenderer.registerReplace(op, d);
		}
	}
}
